import React, { useState, useEffect } from 'react';
import { Row, Col, Typography, message } from 'antd';
import { FireFilled, TeamOutlined, CrownFilled } from '@ant-design/icons';

import { getDashboardData,DashboardData, TopGroup, GenderData, GradeData } from '@/utils/api/index';
import StatCards from '@/components/Dashboard/StatCards';
import TopGroupsList from '@/components/Dashboard/TopGroupsList';
import GenderRatioChart from '@/components/Dashboard/GenderRatioChart';
import GradeDistributionChart from '@/components/Dashboard/GradeDistributionChart';

const { Title } = Typography;

const HomePage: React.FC = () => {
    const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
    const [loading, setLoading] = useState(true);
    const [errorShown, setErrorShown] = useState(false);

    useEffect(() => {
        fetchDashboardData();
    }, []);

    const fetchDashboardData = async () => {


        try {
            setLoading(true);
            setErrorShown(false);
            const response = await getDashboardData();

            if (response.code === 200) {
                setDashboardData(response.data);
            } else {
                console.error('获取数据失败:', response.data?.msg);
                if (!errorShown) {
                    setErrorShown(true);
                }
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            if (!errorShown) {
                setErrorShown(true);
            }
        } finally {
            setLoading(false);
        }
    };

    // 处理人气TOP10小组数据
    const popularGroups: TopGroup[] = dashboardData?.hotGroup
        ?.slice(0, 10)
        .map(item => ({
            id: item.id || null,
            name: item.name || "未命名小组",
            value: item.hot || 0
        })) || [];

    // 处理人数TOP10小组数据
    const memberGroups: TopGroup[] = dashboardData?.numberGroup
        ?.slice(0, 10)
        .map(item => ({
            id: item.id || null,
            name: item.name || "未命名小组",
            value: item.number || 0
        })) || [];

    // 处理活跃度TOP10小组数据
    const activeGroups: TopGroup[] = dashboardData?.logGroup
        ?.slice(0, 10)
        .map(item => ({
            id: item.id || null,
            name: item.name || "未命名小组",
            value: item.logCount || 0
        })) || [];

    // 处理性别比例数据
    const genderData: GenderData[] = dashboardData?.sexCount
        ?.filter(item => item.count !== null && item.count !== undefined)
        .map(item => ({
            type: item.sex === false ? '女生' : '男生',
            value: Number(item.count)
        })) || [];

    // 处理年级人数数据
    const gradeData: GradeData[] = dashboardData?.gradeCount
        ?.filter(item => item.count !== null && item.count !== undefined && item.grade)
        .map(item => ({
            grade: item.grade,
            count: item.count
        })) || [];

    return (
        <div style={{ padding: '24px', background: '#f3f3f3', minHeight: '100vh' }}>
            <Title level={2} style={{ textAlign: 'center', marginBottom: '24px' }}>
                小组管理系统
            </Title>

            <StatCards
                loading={loading}
                groupCount={dashboardData?.group ?? null}
                studentCount={dashboardData?.student ?? null}
                teacherCount={dashboardData?.teacher ?? null}
                logCount={dashboardData?.log ?? null}
            />

            <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                {/* Top10人气小组 */}
                <Col xs={24} md={12} lg={8}>
                    <TopGroupsList
                        loading={loading}
                        title="人气TOP10小组"
                        icon={<FireFilled style={{ color: '#ff4d4f', marginRight: '8px' }} />}
                        dataSource={popularGroups}
                        valueSuffix="人气值"
                    />
                </Col>

                {/* Top10人数小组 */}
                <Col xs={24} md={12} lg={8}>
                    <TopGroupsList
                        loading={loading}
                        title="人数TOP10小组"
                        icon={<TeamOutlined style={{ color: '#1890ff', marginRight: '8px' }} />}
                        dataSource={memberGroups}
                        valueSuffix="成员数"
                    />
                </Col>

                {/* Top10活跃度小组 */}
                <Col xs={24} md={12} lg={8}>
                    <TopGroupsList
                        loading={loading}
                        title="活跃度TOP10小组"
                        icon={<CrownFilled style={{ color: '#faad14', marginRight: '8px' }} />}
                        dataSource={activeGroups}
                        valueSuffix="活跃度"
                    />
                </Col>

                {/* 学生男女占比 */}
                <Col xs={24} md={12}>
                    <GenderRatioChart
                        loading={loading}
                        data={genderData}
                    />
                </Col>

                {/* 年级人数对比 */}
                <Col xs={24} md={12}>
                    <GradeDistributionChart
                        loading={loading}
                        data={gradeData}
                    />
                </Col>
            </Row>
        </div>
    );
};

export default HomePage;